<?php

namespace App\Http\Controllers\Api\Wx;

use Carbon\Carbon;

use GuzzleHttp\Client;

use Faker\Provider\Uuid;

use Illuminate\Http\Request;

use App\Models\Wx\WxAppletDevice;

use App\Models\ConfigureFunction;

use App\Models\Wx\WxAppletCustomer;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\Wx\Pkcs7Encoder;

use App\Service\CartService;

use App\Models\Source\SourceFixedPages;

use App\Models\Goods\GoodsSale;

use App\Service\PromotionService;

use App\Models\Mall\MallMaster;

use App\Models\SysTag;

use App\Models\ConfigureTag;

use App\Models\ConfigureTagRelation;

use App\Models\Goods\GoodsStore;

class WxAppletController extends Controller
{

    /**
     * 微信小程序初始接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function init(Request $request)
    {

        //http实例
        $client = new Client();

        //小程序粉丝信息
        $user_info = $request->input('user_info');
        if (empty($user_info)) {
            $user_info['gender '] = 0;
            $user_info['nickName'] = null;
            $user_info['avatarUrl'] = null;
            $user_info['province'] = null;
            $user_info['city'] = null;
            $user_info['country'] = null;
        }

        $session_id = $request->input('session_id');
        if (empty($session_id)) {
            $session_id = session_id();
        }

        //微信app_id
        $wx_app_id = $request->input('wx_app_id', 'wxbb0a94c33d1c0430');
        if (empty($wx_app_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：wx_app_id']);
        }

        //微信小程序code
        $code = $request->input('code');
        if (empty($code)) {
            return response()->json(['code' => 10001, 'message' => '缺少参数：code']);
        }

        $wx_applet_info = json_decode(Redis::get('WX_APPLET_USER_' . $session_id), true);
        $unionid = null;
        if (!$wx_applet_info || !isset($wx_applet_info['openId'])) {

            $http_data = [
                'applet_app_id' => $wx_app_id,
                'js_code' => $code
            ];
            $response = $client->get('https://wx.ebsig.com/applet/login?' . http_build_query($http_data));
            $code = $response->getStatusCode();
            if ($code != 200) {
                return response()->json(['code' => 10002, 'message' => '微信授权失败']);
            }
            $return_data = json_decode($response->getBody()->getContents(), true);
            if ($return_data['code'] != 200) {
                return response()->json(['code' => 10002, 'message' => '微信授权失败']);
            }

            $wx_applet_info = [
                'openId' => $return_data['data']['openid'],
                'session_key' => $return_data['data']['session_key']
            ];

            if (isset($return_data['data']['unionid'])) {
                $unionid = $return_data['data']['unionid'];
            }

        }

        //保存微信小程序粉丝信息
        $wx_applet_customer = WxAppletCustomer::select('id', 'pcustID')->where('openId', $wx_applet_info['openId'])->first();
        if (!$wx_applet_customer) {

            //根据unionid检查粉丝使用过的其他微信小程序
            //获取使用其他小程序时使用网站会员
            $pcustID = 0;
            if (!empty($unionid)) {
                $temp_wx_applet = WxAppletCustomer::select('pcustID')->where('unionid', $unionid)->get()->toArray();
                if ($temp_wx_applet) {
                    foreach ($temp_wx_applet as &$t) {
                        if (!empty($t['pcustID'])) {
                            $pcustID = $t['pcustID'];
                            break;
                        }
                    }
                }
            }

            $wx_applet_customer = new WxAppletCustomer();
            $wx_applet_customer->uuid = str_replace('-', '', Uuid::uuid());
            $wx_applet_customer->timeStamp = Carbon::now();
            $wx_applet_customer->creator = 'api';
            $wx_applet_customer->createTime = Carbon::now();
            $wx_applet_customer->app_id = $wx_app_id;
            $wx_applet_customer->openId = $wx_applet_info['openId'];
            $wx_applet_customer->unionid = $unionid;
            $wx_applet_customer->pcustID = $pcustID;
            $wx_applet_customer->nickName = $user_info['nickName'];
            $wx_applet_customer->country = $user_info['country'];
            $wx_applet_customer->province = $user_info['province'];
            $wx_applet_customer->city = $user_info['city'];
            $wx_applet_customer->sex = $user_info['gender'];
            $wx_applet_customer->head_pic = $user_info['avatarUrl'];
            $wx_applet_customer->save();

        }
        $wx_applet_info['id'] = $wx_applet_customer->id;
        $wx_applet_info['pcustID'] = $wx_applet_customer->pcustID;
        
        //保存设备信息
        $system_info = $request->input('system_info');
        if ($system_info) {
            $wx_applet_device = new WxAppletDevice();
            $wx_applet_device->uuid = str_replace('-', '', Uuid::uuid());
            $wx_applet_device->timeStamp = Carbon::now();
            $wx_applet_device->createTime = Carbon::now();
            $wx_applet_device->creator = 'api';
            $wx_applet_device->applet_customer_id = $wx_applet_info['id'];
            $wx_applet_device->model = $system_info['model'];
            $wx_applet_device->pixel_ratio = $system_info['pixelRatio'];
            $wx_applet_device->window_width = $system_info['windowWidth'];
            $wx_applet_device->window_height = $system_info['windowHeight'];
            $wx_applet_device->language = $system_info['language'];
            $wx_applet_device->version = $system_info['version'];
            $wx_applet_device->system = $system_info['system'];
            $wx_applet_device->platform = $system_info['platform'];
            $wx_applet_device->dbk_version = $system_info['SDKVersion'];
            $wx_applet_device->save();
        }

        Redis::setex('WX_APPLET_USER_' . $session_id, 604800, json_encode($wx_applet_info, true));

        //获取购物车商品数量
        $cart_amount = CartService::getCartGoodsAmount($session_id);

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => [
            'session_id' => $session_id,
            'openId' => $wx_applet_info['openId'],
            'pcustID' => $wx_applet_info['pcustID'],
            'is_login' => $wx_applet_info['pcustID'] ? 1 : 0,
            'is_open_choose_mall' => ConfigureFunction::getConfigureField(8, 'is_open_choose_mall', 0),
            'company_name' => ConfigureFunction::getConfigureField(48, 'company_name', ''),
            'theme_color' => ConfigureFunction::getConfigure(19),
            'cart_amount' => $cart_amount
        ]]);

    }

    /**
     * 根据session id获取登录微信会员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function get(Request $request)
    {

        $session_id = $request->input('session_id');
        if (empty($session_id)) {
            return response()->json(['code' => 10001, 'message' => '缺少session_id参数']);
        }

        $wx_applet_info = Redis::setex('WX_APPLET_USER_' . $session_id);
        if (!$wx_applet_info) {
            return response()->json(['code' => 10002, 'message' => '粉丝信息不存在']);
        } else {
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => [
                'id' => $wx_applet_info['id'],
                'openId' => $wx_applet_info['openId'],
                'pcustID' => $wx_applet_info['pcustID'],
            ]]);
        }

    }

    /**
     * 微信小程序解密接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function decryptData(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
            $encrypted_data = $request->input('encrypted_data');
        $iv = $request->input('iv');

        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少session_id参数']);
        }

        if (empty($encrypted_data)) {
            return response()->json(['code' => 10001, 'message' => '缺少encrypted_data参数']);
        }

        if (empty($iv)) {
            return response()->json(['code' => 10002, 'message' => '缺少iv参数']);
        }

        $wx_applet_info = json_decode(Redis::get('WX_APPLET_USER_' . $session_id), true);
        if (!$wx_applet_info) {
            return response()->json(['code' => 10002, 'message' => '粉丝信息不存在']);
        }

        $appid = 'wxbb0a94c33d1c0430';
        $session_key = $wx_applet_info['session_key'];

        //实例化配置类
        $Pkcs7Encoder = new Pkcs7Encoder($appid, $session_key);

        $result = $Pkcs7Encoder->decrypt($encrypted_data, $iv);
        if ($result['code'] != 200) {
            return response()->json(['code' => $result['code'], 'message' => $result['data']]);
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $result['data']]);
    }

    //微信小程序首页
    public function index(Request $request)
    {

        $mallID = $request->input('mallID', 1);
        $platform = $request->input('platform', 6);
        $session_id = $request->input('session_id', session_id());

        $pcustID = get_customer_id($session_id, $platform);

        $mall_area_id = 0;
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');
        if ($is_open_choose_mall == 1) {
            if (!ebsig_is_int($mallID)) {
                return response()->json(['code' => 100003, 'message' => '请先选择门店']);
            }

            //查询门店信息
            $mall = MallMaster::getCache($mallID);
            if (!$mall) {
                return response()->json(['code' => 100004, 'message' => '门店不存在']);
            }
            $mall_area_id = $mall['mallareaID'];
        }

        $page = SourceFixedPages::where(['page_platform' => 4, 'page_type' => 6, 'is_use' => 1])->first();
        if (!$page) {
            return response()->json(['code' => 10000, 'message' => '请添加资源信息']);
        }
        $data = $page->toArray();

        $page_set = json_decode($data['page_set_json'], true);

        if (isset($page_set['single']['goods']) && !empty($page_set['single']['goods'])) {

            foreach ($page_set['single']['goods'] as $k => &$sing){
                $sale = GoodsSale::getCache($sing['postID']);
                if (!$sale) {
                    unset($page_set['single']['goods'][$k]);
                    continue;
                }

                $sing['salePrice'] = $sale['salePrice'];
                $sing['salePrice'] = $sale['marketPrice'];
                $sing['spec_num'] = GoodsSale::where(['mainPostID' => $sing['mainPostID']])->count();

                //检查库存及门店销售价格
                if ($is_open_choose_mall) {
                    $sing['enable_sale_amount'] = GoodsStore::search($sale['product_code'], $sale['product_spec'], $mallID);
                } else {
                    $sing['enable_sale_amount'] = GoodsStore::search($sale['product_code'], $sale['product_spec']);
                }

                //商品促销查询
                $promotion_data = PromotionService::goods(array(
                    'postID' => $sale['postID'],
                    'salePrice' => $sale['salePrice'],
                    'salePoints' => isset($sale['salePoints']) ? $sale['salePoints'] : 0,
                    'product_code' => $sale['product_code'],
                    'marketPrice' => $sale['marketPrice'],
                    'goods_amount' => 1,
                    'pcustID' => $pcustID,
                    'mallareaID' => $mall_area_id,
                    'mallID' => $mallID,
                    'platform' => 0
                ));

                if (isset($promotion_data['promotion']) && !empty($promotion_data['promotion'])) {
                    $sing['salePrice'] = $promotion_data['price'];
                    foreach ($promotion_data['promotion'] as $p) {
                        if (isset($p['selected']) && $p['selected'] == 1) {
                            $res_data = SysTag::getCache($p['promotion_type']); //查询商品标签信息
                            if ($res_data) {
                                $sing['pt'][] = $res_data;
                            }
                        }
                    }
                }

                //查询商品标签
                $tag_relation_data = ConfigureTagRelation::where(['relation_id'=>$sing['mainPostID'],'relation_type'=>1])->get()->toArray();
                if ($tag_relation_data) {
                    foreach ($tag_relation_data as $tag) {
                        $reslut_data = ConfigureTag::where(['tag_id'=>$tag['tag_id']])->first();
                        if ($reslut_data) {
                            $reslut_data = $reslut_data->toArray();
                            $sing['pt'][] = $reslut_data;
                        }
                    }
                }


            }
        }

        if (isset($page_set['goods']) && !empty($page_set['goods'])) {
            foreach ($page_set['goods'] as $k => &$g) {
                $sale = GoodsSale::getCache($g['postID']);
                if (!$sale) {
                    unset($page_set['goods']['goods'][$k]);
                    continue;
                }
                $g['salePrice'] = $sale['salePrice'];
                $g['salePrice'] = $sale['marketPrice'];
                $g['spec_num'] = GoodsSale::where(['mainPostID' => $g['mainPostID']])->count();

                //检查库存及门店销售价格
                if ($is_open_choose_mall) {
                    $g['enable_sale_amount'] = GoodsStore::search($sale['product_code'], $sale['product_spec'], $mallID);
                } else {
                    $g['enable_sale_amount'] = GoodsStore::search($sale['product_code'], $sale['product_spec']);
                }

                //商品促销查询
                $promotion_data = PromotionService::goods(array(
                    'postID' => $g['postID'],
                    'salePrice' => $sale['salePrice'],
                    'salePoints' => isset($sale['salePoints']) ? $sale['salePoints'] : 0,
                    'product_code' => $sale['product_code'],
                    'marketPrice' => $sale['marketPrice'],
                    'goods_amount' => 1,
                    'pcustID' => $pcustID,
                    'mallareaID' => $mall_area_id,
                    'mallID' => $mallID,
                    'platform' => 0
                ));
                if (isset($promotion_data['promotion']) && !empty($promotion_data['promotion'])) {
                    $g['salePrice'] = $promotion_data['price'];
                    foreach ($promotion_data['promotion'] as $p) {
                        if (isset($p['selected']) && $p['selected'] == 1) {
                            $res_data = SysTag::getCache($p['promotion_type']); //查询商品标签信息
                            if ($res_data) {
                                $g['pt'][] = $res_data;
                            }
                        }
                    }
                }

                //查询商品标签
                $tag_relation_data = ConfigureTagRelation::where(['relation_id'=>$g['mainPostID'],'relation_type'=>1])->get()->toArray();
                if ($tag_relation_data) {
                    foreach ($tag_relation_data as $tag) {
                        $reslut_data = ConfigureTag::where(['tag_id'=>$tag['tag_id']])->first();
                        if ($reslut_data) {
                            $reslut_data = $reslut_data->toArray();
                            $g['pt'][] = $reslut_data;
                        }
                    }
                }
            }
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $page_set]);
    }
}